package lesson.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lesson.entity.Academy;
import lesson.entity.Team;
import lesson.entity.User;
import lesson.service.AcademyService;
import lesson.service.RoleService;
import lesson.service.TeamService;
import lesson.service.UserService;
import lesson.vo.DataView;
import lesson.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.annotation.RequestScope;

import javax.xml.crypto.Data;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Wanzhen
 * @Date: 2022/6/13-12:24
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private AcademyService academyService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/toUser")
    public String toUser(){
        return "user/user";
    }

    //个人信息
    @RequestMapping("/toUserInfo")
    public String toUserInfo(){
        return "/user/userInfo";
    }

    //修改密码
    @RequestMapping("/toChangePassword")
    public String toChangePassword(){
        return "/user/chagepassword";
    }

    /**
     * 分页查询所有的用户数据，带有查询条件
     * @param userVo
     * @return
     */
    @RequestMapping("/loadAllUser")
    @ResponseBody
    public DataView getAllUser(UserVo userVo){
        //1.第一种方法
        /*if(StringUtils.isNotBlank(userVo.getUsername())){
            userService.loadUserByLeftJoin(userVo.getUsername(), userVo.getPage(), userVo.getLimit());
        }*/
        //在UserMapper中使用@Select注解
        //(SELECT a.username,b.name FROM user_tbl a LEFT JOIN `group` b ON a.group_id = b.id limit #{}, #{})

        //2.第二种方法
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> page = new Page<>(userVo.getPage(), userVo.getLimit());
           //模糊查询
        queryWrapper.like(StringUtils.isNotBlank(userVo.getUsername()), "username", userVo.getUsername());
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getPhone()), "phone", userVo.getPhone());
        IPage<User> iPage = userService.page(page, queryWrapper);

        //从获取的记录中再进行查询
        for(User user : iPage.getRecords()){
            //为班级名字进行赋值
            if(user.getTeamId() != null){
                //班级Service查库
                Team group = teamService.getById(user.getTeamId());
                user.setTeamName(group.getName());
            }
            //为学院名字进行赋值
            if(user.getAcademyId() != null){
                Academy academy = academyService.getById(user.getAcademyId());
                user.setAcademyName(academy.getName());
            }
            //为老师名字进行赋值
            if(user.getTeacherId() != null){
                User teacher = userService.getById(user.getTeacherId());
                user.setTeacherName(teacher.getUsername());
            }
        }

        return new DataView(iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 新增用户
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public DataView addUser(User user){
        boolean save = userService.save(user);
        DataView dataView = new DataView();
        dataView.setMsg("添加用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    //修改用户
    @RequestMapping("/updateUser")
    @ResponseBody
    private DataView updateUser(User user){
        userService.updateById(user);
        DataView dataView = new DataView();
        dataView.setMsg("修改用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    //删除用户，结合前段代码发现是，取路径上的id
    @RequestMapping("/deleteUser/{id}")
    @ResponseBody
    public DataView deleteUser(@PathVariable("id") Integer id){
        userService.removeById(id);
        DataView dataView = new DataView();
        dataView.setMsg("删除用户成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 初始化下拉列表的数据[班级]
     */
    @RequestMapping("/listAllTeam")
    @ResponseBody
    public List<Team> ListAllTeam(){
        List<Team> list = teamService.list();
        return list;
    }

    /**
     * 初始化下拉列表的数据[学院]
     */
    @RequestMapping("/listAllAcademy")
    @ResponseBody
    public List<Academy> ListAllAcademy(){
        List<Academy> list = academyService.list();
        return list;
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd/{id}")
    @ResponseBody
    public DataView resetPwd(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        user.setPassword("123456");
        userService.updateById(user);
        DataView dataView = new DataView();
        dataView.setMsg("当前用户重置密码成功！");
        dataView.setCode(200);
        return dataView;
    }

    /**
     * 打开分配角色的弹层
     * 当点击分配时候，初始化用户角色
     * 根据ID查询所拥有的角色
     */
    @RequestMapping("/initRoleByUserId")
    @ResponseBody
    public DataView initRoleByUserId(Integer id){
        //1.查询所有角色
        List<Map<String, Object>> listMaps = roleService.listMaps();
        //2.查询当前登录用户所拥有的角色
        List<Integer> currentUserRoleIds = roleService.queryUserRoleById(id);
        //在前端中，都变成选中状态
        for(Map<String, Object> map : listMaps){
            Boolean LAY_CHECKED = false;
            Integer roleId = (Integer) map.get("id");
            for(Integer rid : currentUserRoleIds){
                if(rid.equals(roleId)){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED", LAY_CHECKED);
        }
        return new DataView(Long.valueOf(listMaps.size()), listMaps);
    }

    /**
     * 保存用户与角色之间的关系 1:m
     * 先删除，再保存关系
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public DataView saveUserRole(Integer uid, Integer[] ids){
        userService.saveUserRole(uid, ids);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("用户的角色分配成功");
        return dataView;
    }

}
